package fun.flyee.android.pengshan.widgets;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fun.flyee.pengshan.social.R;
import fun.flyee.android.pengshan.utils.Logger;

public class SearchBar extends LinearLayout {

    @BindView(R.id.keyword_view)
    public EditText keywordView;
    @BindView(R.id.clear_icon)
    public View clearBtn;

    private OnSearchListener listener;
    private OnChangeListener listener1;

    public SearchBar(Context context) {
        super(context);
        init();
    }

    public SearchBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SearchBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View.inflate(getContext(), R.layout.search_bar, this);
        ButterKnife.bind(this, this);
        keywordView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    clearBtn.setVisibility(INVISIBLE);
                } else {
                    clearBtn.setVisibility(VISIBLE);
                }
                if(listener1!=null){
                    listener1.onChanged(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        keywordView.setOnEditorActionListener((view, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (listener != null) {
                    String keyword = keywordView.getText().toString().trim();
                    listener.onSearch(keyword);
                }
            }
            return false;
        });
    }

    public void setSearchListener(OnSearchListener listener) {
        this.listener = listener;
    }

    public void setChangedListener(OnChangeListener listener) {
        this.listener1 = listener;
    }

    public void setHint(String text) {
        keywordView.setHint(text);
    }

    @OnClick(R.id.clear_icon)
    public void onClear(View v) {
        keywordView.setText("");
    }

    public interface OnSearchListener {
        void onSearch(String keyword);
    }

    public interface OnChangeListener {
        void onChanged(String keyword);
    }
}
